package com.jadcon.bedbreakfast.web;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.jadcon.bedbreakfast.domain.Reservation;
import com.jadcon.bedbreakfast.domain.ReservationService;
import com.jadcon.bedbreakfast.domain.ReservationValidator;

@Controller
@SessionAttributes("newReservation")
public class AddReservationController {

	@Autowired
	private ReservationService reservationService;

	@RequestMapping("/addReservation.html")
	public ModelAndView addReservation(HttpSession session) {

		Reservation newReservation = new Reservation();
		ModelAndView mav = new ModelAndView("addReservation");
		mav.addObject("newReservation", newReservation);
		session.setAttribute("newReservation", newReservation);
		return mav;

	}
	
	@RequestMapping("/addReservationConfirm.html")
	public ModelAndView confirmReservation(@RequestParam String submit,
			@ModelAttribute("newReservation") Reservation newReservation, BindingResult result, HttpSession session) {
		
		System.out.println("ReservationController.confirmReservation() begin...");
		Object user  = session.getAttribute("user");
		ReservationValidator reservationValidator = new ReservationValidator();
		reservationValidator.validate(newReservation, result);
		if (result.hasErrors()){
			System.out.println("Validation errors exist, going back to 'addReservation'");
			return new ModelAndView("addReservation"); 
		}

		ModelAndView mav = new ModelAndView("addReservationConfirm"); 
		mav.addObject("newReservation", newReservation); 
		return mav;
	}

	// method that handles the form submission
	@RequestMapping("/saveReservation.html")
	public ModelAndView saveNewReservation(
			@ModelAttribute("newReservation") Reservation newReservation) {

		System.out.println("ReservationController.saveReservation() begin: "
				+ newReservation);
		reservationService.save(newReservation);
		ModelAndView mav = new ModelAndView("saveReservation");
		mav.addObject(newReservation);
		return mav;
	}
	
	@InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }


}
